var express = require('express');
var router = express.Router();
const multiparty = require('multiparty');
const nodemailer = require('nodemailer');
const { userModel, roleModel } = require('../../model/model');
const jwt=require('jsonwebtoken')

const secretKey = 'whisper';
const port = 3000;
//设置nodemailer(以qq邮箱SMTP为例，需开启SMTP服务并获取授权码)
//nodemailer.createTransport 是一个用于创建邮件传输代理的函数，
//可以用来发送电子邮件。
//它接受一个对象作为参数，其中包含有关如何连接到邮件服务器以及如何发送电子邮件的信息。
let transporter = nodemailer.createTransport({
    service: 'qq',
    auth: {
        user: '2356263360@qq.com',
        pass: 'kkclynxvgppkeceg'//授权码
    }
});


router.post('/sendEmail', async (req, res) => {
    const { email } = req.body;
    let result = ''
    const characters = '0123456789';
    for (let i = 0; i < 4; i++) {
        result += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    let code = result;

    let mailOptions = {
        from: '2356263360@qq.com',//发送者地址
        to: email,
        subject: '验证码',//主题行
        text: '验证码：' + code,
    };

    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
            return res.status(500).send('邮件发送失败');
        }
    })

    res.send({
        code: 200,
        msg: '发送成功'
    })

})






//图片上传
router.post('/upload', async (req, res) => {
    let form = new multiparty.Form();
    form.uploadDir = 'upload'
    form.parse(req, (err, file, data) => {
        res.send({
            code: 200,
            msg: '上传成功',
            path: data.file[0].path
        })
    })
})


//登录
// router.post('/login', async (req, res) => {
//     let { email, pwd } = req.body;
//     let user = await userModel.findOne({ email: email, pwd: pwd });
//     if (user) {
//         res.send({ code: 200, msg: '登录成功', data: user })
//     } else {
//         // 登录失败
//         res.send({ code: 400, msg: '用户名或密码错误' })
//     }
// }
// )

router.post('/login', async (req, res) => {
    let { email, pwd } = req.body;
    let user = await userModel.findOne({ email: email, pwd: pwd });
    if (user) {
        const accessToken =jwt.sign({email:user.email},secretKey,{expiresIn:'15m'})
        const refreshToken = jwt.sign({email:user.email},secretKey,{expiresIn:'1d'})
        res.send({ 
            code: 200, 
            msg: '登录成功', 
            data: user,
            accessToken:accessToken,
            refreshToken:refreshToken
        })
    } else {
        // 登录失败
        res.send({ code: 400, msg: '用户名或密码错误' })
    }
}
)

router.post('/refresh-token',(req,res)=>{
    const refreshToken = req.body.token;
    if(refreshToken){
        jwt.verify(refreshToken,secretKey,(err,decoded)=>{
            if(err){
                //如果refresh Token无效，返回错误
                res.status(401).send('Invalid refresh token');
            }else{
                const accessToken = jwt.sign({email:decoded.email},secretKey,{expiresIn:'15m'})
                res.json({
                    accessToken:accessToken
                })
            }
        })
    }else{
        res.status(401).send('No refresh token provided');
    }
})






//注册新用户
router.post('/adduser', (req, res) => {
    userModel.create(req.body)

    res.send({
        code: 200,
        msg: '添加成功'
    })

})

//修改密码
router.post('/updatepwd', async (req, res) => {
    let { email, newpwd } = req.body;
    await userModel.updateOne({ email: email }, { pwd: newpwd })

    res.send({
        code: 200,
        msg: '修改成功'
    })
})

module.exports = router;